package com.xiaochong.tir.manager.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.common.data.po.Account;
import com.xiaochong.tir.common.data.po.AccountRole;
import com.xiaochong.tir.common.data.po.RoleNavigation;
import com.xiaochong.tir.manager.filter.SessionManager;
import com.xiaochong.tir.manager.service.AccountRoleService;
import com.xiaochong.tir.manager.service.NavigationService;
import com.xiaochong.tir.manager.service.RoleNavigationService;
import com.xiaochong.tir.manager.util.ManagerVersion;
import com.xiaochong.tir.manager.util.MenuTreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping(value = ManagerVersion.API_V1_PREFIX+"/data")
@Api(value = "左侧菜单查询")
public class DataController {

	@Autowired
	private NavigationService navigationService;
	@Autowired
	private RoleNavigationService roleNavigationService;
	@Autowired
	private AccountRoleService accountRoleService;

	/**
	 * 获得导航栏数据
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/nav.json")
	public String navJson(HttpSession session) {
		try {
			Account account = SessionManager.getLoginAccount(session);
			if (account == null) {
				return "[]";
			}
			List<JSONObject> all = navigationService.getAllNavigation();
			return JSON.toJSONString(all);
		} catch (Exception ce) {
			LogTrace.error(getClass().getSimpleName() + "/nav.json", ce.getMessage(), ce);
			return "[]";
		}
	}

	/**
	 * 获得导航栏数据-新版
	 * 
	 * @param session
	 * @return
	 */
	@ApiOperation(value = "查询菜单列表",notes = "查询菜单列表")
	@RequestMapping(value = "/navigation.json")
	@ResponseBody
	public Object navigationJson(HttpSession session) {
		try {
			Account account = SessionManager.getLoginAccount(session);
			if (account == null) {
				return "[]";
			}
			// 查询用户角色
			AccountRole accountRole = new AccountRole();
			accountRole.setAccountId(account.getId());
			String roles = accountRoleService.getRolesByAccountId(accountRole);
			RoleNavigation roleNavigation = new RoleNavigation();
			roleNavigation.setRoleIds(roles == null ? "0" : roles);
			List<com.xiaochong.tir.common.data.po.Navigation> list = roleNavigationService
					.getNavigationByRoleId(roleNavigation);
			MenuTreeUtil menuTree = new MenuTreeUtil();
			List<Object> menuList = menuTree.menuList2(list);
			return menuList;
		} catch (Exception e) {
			LogTrace.error(getClass().getSimpleName() + "/navigation.json", e.getMessage(), e);
			return "[]";
		}
	}

}
